//
//  UIPlaceHolderTextView.swift
//  Edaixi-iOS
//
//  Created by 刘树华 on 2017/12/1.
//  Copyright © 2017年 刘树华. All rights reserved.
//

import Foundation
import UIKit
class PlaceHolderTextView:UITextView  {
    var placeHolderStr : String?{
        willSet {
            placeLabel.text = newValue
        }
    }
    var placeHolderColor = UIColor.lightGray
    private let topPadding : CGFloat = 5
    private let horizonPadding : CGFloat = 8
    private var place = ""
    private var placeLabel : UILabel!
    init(placeHolder:String) {
        super.init(frame: CGRect.zero, textContainer: nil)
        NOTIFICATIONCENTER.addObserver(self, selector: #selector(PlaceHolderTextView.textBegin(noti:)), name: NSNotification.Name.UITextViewTextDidChange, object: nil)
        placeLabel = UILabel(text: placeHolder, textAlignment: .left, textColor: placeHolderColor, bgColor: UIColor.clear)
        placeLabel.translatesAutoresizingMaskIntoConstraints = false
        placeLabel.numberOfLines = 0
        self.addSubview(placeLabel)
        placeHolderStr = placeHolder
        
        self.addConstraint(NSLayoutConstraint(item: placeLabel, attribute: NSLayoutAttribute.top, relatedBy: NSLayoutRelation.equal, toItem: self, attribute: .top, multiplier: 1, constant: topPadding))
        self.addConstraint(NSLayoutConstraint(item: placeLabel, attribute: NSLayoutAttribute.left, relatedBy: NSLayoutRelation.equal, toItem: self, attribute: .left, multiplier: 1, constant: horizonPadding))
         self.addConstraint(NSLayoutConstraint(item: placeLabel, attribute: NSLayoutAttribute.right, relatedBy: NSLayoutRelation.equal, toItem: self, attribute: .right, multiplier: 1, constant: horizonPadding))
    }
    @objc private func textBegin(noti:NSNotification){
        if let place = placeHolderStr {
            if place.isEmpty {
                return
            }
        }
        UIView.animate(withDuration: 0.2) {
            if self.text.isEmpty {
                self.placeLabel.alpha = 1
            }else{
                self.placeLabel.alpha = 0
            }
        }
        
    }
    
    deinit {
        NOTIFICATIONCENTER.removeObserver(self)
    }
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }
    
}
